<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">预订管理</h1>
      <p class="page-description">查看和管理所有预订信息</p>
    </div>
    
    <!-- 筛选器 -->
    <a-card class="filter-card" :bordered="false">
      <div class="filter-container">
        <a-form :model="filters" @submit="handleSearch" class="filter-form" :label-col-style="{ width: '80px', flexShrink: 0 }">
          <!-- 第一行 -->
          <div class="filter-row">
            <a-form-item label="房间号" class="filter-item">
              <a-input
                v-model="filters.room_number"
                placeholder="搜索房间号"
                allow-clear
                style="width: 180px"
              />
            </a-form-item>
            
            <a-form-item label="入住日期" class="filter-item">
              <a-date-picker
                v-model="filters.checkin_date"
                placeholder="选择入住日期"
                style="width: 180px"
              />
            </a-form-item>
            
            <a-form-item class="button-group">
              <a-space :size="8">
                <a-button type="primary" html-type="submit" :loading="reservationStore.loading">
                  <template #icon>
                    <icon-search />
                  </template>
                  搜索
                </a-button>
                <a-button @click="handleReset">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </div>
          
          <!-- 第二行 -->
          <div class="filter-row">
            <a-form-item label="预订状态" class="filter-item">
              <a-select
                v-model="filters.status"
                placeholder="选择状态"
                allow-clear
                style="width: 180px"
              >
                <a-option
                  v-for="option in reservationStore.statusOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-option>
              </a-select>
            </a-form-item>
            
            <a-form-item label="退房日期" class="filter-item">
              <a-date-picker
                v-model="filters.checkout_date"
                placeholder="选择退房日期"
                style="width: 180px"
              />
            </a-form-item>
          </div>
        </a-form>
        
        <div class="action-buttons">
          <a-space :size="12">
            <a-button type="primary" @click="handleAddReservation">
              <template #icon>
                <icon-plus />
              </template>
              新建预订
            </a-button>
            <a-button @click="handleExport">
              <template #icon>
                <icon-download />
              </template>
              导出数据
            </a-button>
          </a-space>
        </div>
      </div>
    </a-card>
    
    <!-- 预订列表 -->
    <a-card class="table-card" :bordered="false">
      <a-table
        :columns="columns"
        :data="reservationStore.reservations"
        :loading="reservationStore.loading"
        :pagination="paginationConfig"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #status="{ record }">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>
        
        <template #totalAmount="{ record }">
          ¥{{ record.total_amount?.toLocaleString() || 0 }}
        </template>
        
        <template #actions="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleViewReservation(record)">
              <template #icon>
                <icon-eye />
              </template>
              查看
            </a-button>
            <a-button 
              v-if="record.status === 1" 
              type="text" 
              size="small" 
              @click="handleConfirmReservation(record.id)"
            >
              <template #icon>
                <icon-check />
              </template>
              确认
            </a-button>
            <a-button 
              v-if="record.status === 1 || record.status === 2" 
              type="text" 
              size="small" 
              @click="handleEditReservation(record)"
            >
              <template #icon>
                <icon-edit />
              </template>
              编辑
            </a-button>
            <a-button 
              v-if="record.status === 1 || record.status === 2" 
              type="text" 
              size="small" 
              status="danger"
              @click="handleCancelReservation(record.id)"
            >
              <template #icon>
                <icon-close />
              </template>
              取消
            </a-button>
            <a-popconfirm
              content="确定要删除这个预订吗？"
              @ok="handleDeleteReservation(record.id)"
            >
              <a-button type="text" size="small" status="danger">
                <template #icon>
                  <icon-delete />
                </template>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>
    
    <!-- 预订表单模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :width="800"
      :ok-text="modalMode === 'view' ? '关闭' : '确定'"
      :hide-cancel="modalMode === 'view'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="客户姓名" field="guest_name">
              <a-input 
                v-model="formData.guest_name" 
                placeholder="请输入客户姓名"
                :disabled="modalMode === 'view'"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="客户电话" field="guest_phone">
              <a-input 
                v-model="formData.guest_phone" 
                placeholder="请输入客户电话"
                :disabled="modalMode === 'view'"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="房间号" field="room_number">
              <a-input 
                v-model="formData.room_number" 
                placeholder="请输入房间号"
                :disabled="modalMode === 'view'"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="预订状态" field="status">
              <a-select
                v-model="formData.status"
                placeholder="请选择预订状态"
                :disabled="modalMode === 'view'"
                style="width: 100%"
              >
                <a-option
                  v-for="option in reservationStore.statusOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="入住日期" field="checkin_date">
              <a-date-picker
                v-model="formData.checkin_date"
                placeholder="请选择入住日期"
                :disabled="modalMode === 'view'"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="退房日期" field="checkout_date">
              <a-date-picker
                v-model="formData.checkout_date"
                placeholder="请选择退房日期"
                :disabled="modalMode === 'view'"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="入住人数" field="guest_count">
              <a-input-number
                v-model="formData.guest_count"
                placeholder="请输入入住人数"
                :min="1"
                :disabled="modalMode === 'view'"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="总金额" field="total_amount">
              <a-input-number
                v-model="formData.total_amount"
                placeholder="请输入总金额"
                :min="0"
                :precision="2"
                :disabled="modalMode === 'view'"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="特殊要求" field="special_requests">
          <a-textarea
            v-model="formData.special_requests"
            placeholder="请输入特殊要求"
            :rows="3"
            :disabled="modalMode === 'view'"
          />
        </a-form-item>
        
        <a-form-item label="备注" field="notes">
          <a-textarea
            v-model="formData.notes"
            placeholder="请输入备注"
            :rows="2"
            :disabled="modalMode === 'view'"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useReservationStore } from '@/stores/reservation'
import { confirmReservation, cancelReservation } from '@/api/reservation'
import { Message } from '@arco-design/web-vue'
import {
  IconPlus,
  IconSearch,
  IconRefresh,
  IconEye,
  IconEdit,
  IconDelete,
  IconCheck,
  IconClose,
  IconDownload
} from '@arco-design/web-vue/es/icon'

const reservationStore = useReservationStore()

// 筛选条件
const filters = reactive({
  room_number: '',
  status: '',
  checkin_date: '',
  checkout_date: ''
})

// 模态框状态
const modalVisible = ref(false)
const modalTitle = ref('')
const modalMode = ref('add') // add | edit | view
const currentReservationId = ref(null)

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive({
  guest_name: '',
  guest_phone: '',
  room_number: '',
  status: 1,
  checkin_date: '',
  checkout_date: '',
  guest_count: 1,
  total_amount: 0,
  special_requests: '',
  notes: ''
})

// 表单验证规则
const formRules = {
  guest_name: [
    { required: true, message: '请输入客户姓名' }
  ],
  guest_phone: [
    { required: true, message: '请输入客户电话' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
  ],
  room_number: [
    { required: true, message: '请输入房间号' }
  ],
  checkin_date: [
    { required: true, message: '请选择入住日期' }
  ],
  checkout_date: [
    { required: true, message: '请选择退房日期' }
  ],
  guest_count: [
    { required: true, message: '请输入入住人数' },
    { type: 'number', min: 1, message: '入住人数必须大于0' }
  ]
}

// 表格列配置
const columns = [
  { title: '预订编号', dataIndex: 'reservation_number', width: 140 },
  { title: '客户姓名', dataIndex: 'guest_name', width: 120 },
  { title: '房间号', dataIndex: 'room_number', width: 100 },
  { title: '入住日期', dataIndex: 'checkin_date', width: 120 },
  { title: '退房日期', dataIndex: 'checkout_date', width: 120 },
  { title: '状态', slotName: 'status', width: 100 },
  { title: '总金额', slotName: 'totalAmount', width: 120 },
  { title: '操作', slotName: 'actions', width: 200, fixed: 'right' }
]

// 分页配置
const paginationConfig = computed(() => ({
  current: reservationStore.pagination.current,
  pageSize: reservationStore.pagination.size,
  total: reservationStore.pagination.total,
  showTotal: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50, 100]
}))

// 获取状态颜色
const getStatusColor = (status) => {
  const colors = {
    1: 'orange',  // 待确认
    2: 'blue',    // 已确认
    3: 'green',   // 已入住
    4: 'red'      // 已取消
  }
  return colors[status] || 'gray'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    1: '待确认',
    2: '已确认',
    3: '已入住',
    4: '已取消'
  }
  return texts[status] || '未知'
}

// 处理搜索
const handleSearch = () => {
  reservationStore.setFilters(filters)
  reservationStore.fetchReservations()
}

// 处理导出数据
const handleExport = () => {
  try {
    const exportData = reservationStore.reservations.map(reservation => ({
      '预订ID': reservation.id,
      '客户姓名': reservation.guest_name || '-',
      '客户电话': reservation.guest_phone || '-',
      '房间号': reservation.room_number || '-',
      '预订状态': getStatusText(reservation.status),
      '入住日期': reservation.checkin_date || '-',
      '退房日期': reservation.checkout_date || '-',
      '入住人数': reservation.guest_count || 0,
      '总金额(元)': reservation.total_amount || 0,
      '特殊要求': reservation.special_requests || '-',
      '备注': reservation.notes || '-'
    }))

    const headers = Object.keys(exportData[0])
    const csvContent = [
      headers.join(','),
      ...exportData.map(row => headers.map(header => {
        const value = row[header]
        if (typeof value === 'string' && (value.includes(',') || value.includes('\n'))) {
          return `"${value.replace(/"/g, '""')}"`
        }
        return value
      }).join(','))
    ].join('\n')

    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
    
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `预订数据_${new Date().toLocaleDateString()}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    Message.success('导出成功！')
  } catch (error) {
    console.error('导出失败:', error)
    Message.error('导出失败，请重试')
  }
}

// 处理重置
const handleReset = () => {
  reservationStore.resetFilters()
  Object.assign(filters, {
    room_number: '',
    status: '',
    checkin_date: '',
    checkout_date: ''
  })
  reservationStore.fetchReservations()
}

// 处理分页变化
const handlePageChange = (page) => {
  reservationStore.setPagination({ current: page })
  reservationStore.fetchReservations()
}

// 处理页面大小变化
const handlePageSizeChange = (pageSize) => {
  reservationStore.setPagination({ current: 1, size: pageSize })
  reservationStore.fetchReservations()
}

// 处理添加预订
const handleAddReservation = () => {
  modalMode.value = 'add'
  modalTitle.value = '新建预订'
  resetForm()
  modalVisible.value = true
}

// 处理查看预订
const handleViewReservation = (record) => {
  modalMode.value = 'view'
  modalTitle.value = '预订详情'
  fillForm(record)
  modalVisible.value = true
}

// 处理编辑预订
const handleEditReservation = (record) => {
  modalMode.value = 'edit'
  modalTitle.value = '编辑预订'
  currentReservationId.value = record.id
  fillForm(record)
  modalVisible.value = true
}

// 处理确认预订
const handleConfirmReservation = async (id) => {
  try {
    const response = await confirmReservation(id)
    if (response.success) {
      Message.success('预订确认成功')
      reservationStore.fetchReservations()
    } else {
      Message.error(response.message || '确认失败')
    }
  } catch (error) {
    Message.error('确认失败，请检查网络连接')
  }
}

// 处理取消预订
const handleCancelReservation = async (id) => {
  try {
    const response = await cancelReservation(id)
    if (response.success) {
      Message.success('预订取消成功')
      reservationStore.fetchReservations()
    } else {
      Message.error(response.message || '取消失败')
    }
  } catch (error) {
    Message.error('取消失败，请检查网络连接')
  }
}

// 处理删除预订
const handleDeleteReservation = async (id) => {
  await reservationStore.deleteReservationData(id)
}

// 处理模态框确认
const handleModalOk = async () => {
  if (modalMode.value === 'view') {
    modalVisible.value = false
    return
  }
  
  const valid = await formRef.value.validate()
  if (!valid) return
  
  let success = false
  if (modalMode.value === 'add') {
    success = await reservationStore.createReservationData(formData)
  } else if (modalMode.value === 'edit') {
    success = await reservationStore.updateReservationData(currentReservationId.value, formData)
  }
  
  if (success) {
    modalVisible.value = false
  }
}

// 处理模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
}

// 填充表单
const fillForm = (record) => {
  Object.assign(formData, {
    guest_name: record.guest_name || '',
    guest_phone: record.guest_phone || '',
    room_number: record.room_number || '',
    status: record.status || 1,
    checkin_date: record.checkin_date || '',
    checkout_date: record.checkout_date || '',
    guest_count: record.guest_count || 1,
    total_amount: record.total_amount || 0,
    special_requests: record.special_requests || '',
    notes: record.notes || ''
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    guest_name: '',
    guest_phone: '',
    room_number: '',
    status: 1,
    checkin_date: '',
    checkout_date: '',
    guest_count: 1,
    total_amount: 0,
    special_requests: '',
    notes: ''
  })
  formRef.value?.resetFields()
}

// 组件挂载时获取数据
onMounted(() => {
  reservationStore.fetchReservations()
})
</script>

<style scoped lang="scss">
.filter-card {
  margin-bottom: 12px;
  
  :deep(.arco-card-body) {
    padding: 12px 16px;
  }
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12px;
  
  @media (max-width: 1024px) {
    flex-direction: column;
    gap: 8px;
  }
}

.filter-form {
  flex: 1;
  min-width: 0;
}

.filter-row {
  display: grid;
  grid-template-columns: 240px 240px auto;
  gap: 8px 12px;
  align-items: center;
  margin-bottom: 8px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  @media (max-width: 1200px) {
    grid-template-columns: 240px 240px;
  }
  
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
    gap: 8px;
  }
}

.filter-item {
  display: flex;
  align-items: center;
  
  :deep(.arco-form-item) {
    margin-bottom: 0;
    width: 100%;
    display: flex;
    align-items: center;
  }
  
  :deep(.arco-form-item-label-col) {
    width: 70px;
    flex: 0 0 70px;
    padding-right: 6px;
  }
  
  :deep(.arco-form-item-label) {
    font-weight: 500;
    color: #1d2129;
    white-space: nowrap;
    text-align: right;
    width: 100%;
    font-size: 13px;
  }
  
  :deep(.arco-form-item-wrapper-col) {
    flex: 1;
    min-width: 0;
  }
  
  :deep(.arco-input-wrapper),
  :deep(.arco-select-view),
  :deep(.arco-picker) {
    width: 100%;
    max-width: 160px;
    min-width: 160px;
  }
}

.button-group {
  grid-column: 3;
  grid-row: 1;
  display: flex;
  justify-content: flex-end;
  
  :deep(.arco-form-item) {
    margin-bottom: 0;
  }
  
  @media (max-width: 1200px) {
    grid-column: 1 / -1;
    grid-row: auto;
    margin-top: 4px;
    justify-content: flex-end;
  }
  
  @media (max-width: 768px) {
    width: 100%;
    
    :deep(.arco-space) {
      width: 100%;
      display: flex;
      
      .arco-btn {
        flex: 1;
      }
    }
  }
}

.action-buttons {
  flex-shrink: 0;
  
  @media (max-width: 1024px) {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
  
  @media (max-width: 768px) {
    :deep(.arco-space) {
      width: 100%;
      display: flex;
      
      .arco-btn {
        flex: 1;
      }
    }
  }
}

.table-card {
  margin-bottom: 16px;
}
</style>
